<?php

if (!defined('BASEPATH'))
	exit('No direct script access allowed');

/**
 * Description of MY_Controller
 *
 * @author Admin
 */
class MY_Controller extends CI_Controller {

	// Mang truyen bien sang view
	protected $data;
	// Load config tu csdl
	protected $siteConfig;
	// Style hien tai cua trang
	protected $style;
	// Ngon ngu nguoi dung stdClass
	protected $user_lang;
	// Tat car ngon ngu cua trang stdClass array
	protected $languages;
	// Lay location luu o client
	protected $location;
	// Thong tin user hien tai
	protected $user = false;
	var $ajax = false;
	private $inAdminFolder = false;

	function __construct() {
		parent::__construct();

		$this->load->helper('language');
		$this->load->helper('debug');
		$this->load->helper('user');
		$this->load->helper('global');
		$this->load->helper('cookie');
		$this->load->helper('style');
		$this->load->driver('cache');
		$this->load->helper('date');

		$admin_folder = $this->config->item('admin_folder');

		//Detect ajax request
		$header = $this->input->request_headers();
		if (isset($header['Accept'])) {
			$accept = $header['Accept'];
			if (strpos($accept, 'application/json') !== false)
				$this->ajax = true;
		}

		//Load config
		$this->siteConfig = uconfig_get();
		$this->data['config'] = $this->siteConfig;

		//Load style
		$this->style = style_get($this->siteConfig->style);

		// 
		if ($this->session->userdata('user_id') === FALSE)
			$this->session->set_userdata('user_id', $this->siteConfig->guest_id);
		$this->user = $this->getUserInfo();

		//Load config
//		if(!$this->siteConfig=$this->cache->file->get('siteConfig'))
//		{
			$this->siteConfig = uconfig_get();
//			$this->cache->file->save('siteConfig',$this->siteConfig,1);
//		}
		
		$this->data['config'] = $this->siteConfig;

		//Load style
		$this->style = style_get($this->siteConfig->style);

		$this->languages = lang_get_all();
		$this->data['langs'] = $this->languages;

		//Load language
		$this->get_user_lang();
		$this->data['lang'] = $this->user_lang->id;

		if ($this->session->userdata('cart') === FALSE)
			$this->session->set_userdata('cart', array());
		
		switch ($this->uri->segment(1)) {
			case $admin_folder: {
					$this->inAdminFolder = true;
					if ($this->uri->total_segments() == 1)
						redirect(url_create('admin', 'dashboard'));

					if ($this->uri->segment(2) != 'login') {
						if (!$this->isUserLogin()) {
							redirect($admin_folder . '/login?ref=' . $this->uri->uri_string());
						}
						if (!$this->checkPermission()) {
							if ($this->ajax)
								echo json_encode(array(
									'state' => 'error',
									'title' => lang('error'),
									'message' => lang('not_authentication'),
								));
							else
							if ($this->isUserLogin())
								show_error(lang('not_authentication'));
							else {
								redirect(url_create('admin', 'login', 'index') . '?ref=' . urlencode(site_url($this->uri->ruri_string())));
							}
						}
					}


					// Load cac module bang dieu khien
					$this->load->model('model_module');
					$modules = $this->model_module->get_list_hash(array(
						'order' => array('index', 'asc')
							));

					$where = array();
					if (!$this->isRootAdmin())
						$where['active'] = true;
					$menus = $this->model_module->get_list_hash(array(
						'where' => $where,
						'order' => array('index', 'asc')
							));


					array_to_object($menus);

					//Tick module hien tai va cac module cap  tren
					$curr_controller = $this->uri->segment(2) != '' ? $this->uri->segment(2) : $this->config->item('default_controller');

					$curr_controller_id = $this->model_module->get_id(array('controller' => $curr_controller));

					$breadcrumb = breadcrumb_create($modules, $curr_controller_id);

					$this->data['breadcrumb'] = $breadcrumb;
					$this->data['active_menu_id'] = $curr_controller_id;
					$this->data['menus'] = $menus;
					$this->data['modules'] = $modules;
					break;
				}
			default: {

					$this->load->model('model_catalogue');
					$this->load->model('model_location');

					//Lay danh sach dia diem
					$locations = $this->model_location->get_list_hash(array(
						'order' => array('index', 'asc')
							));
					$this->data['locations'] = $locations;

					//Lay dia diem cua nguoi dung
					$this->location = $this->get_user_location();

					if (!$catalogues = $this->cache->file->get('catalogues_' . $this->location)) {
						$catalogues = $this->model_catalogue->get_list_hash($this->siteConfig->lang, array(
							'order' => array('index', 'asc')
								));
						$this->load->model('model_product');
						$this->load->helper('date');
						foreach ($catalogues as $id => $row) {
							$catalogues[$id]->p_amount = $this->model_product->get_total(array(
								'end >=' => now(),
								'l.location_id' => $this->location,
								'c.cat_id' => $row->id,
									));
						}
						array_to_object($catalogues);

						$this->cache->file->save('catalogues_' . $this->location, $catalogues, 5);
					}

					$this->data['catalogues'] = $catalogues;
					$this->data['current_location'] = $this->location;
					$this->data['is_home'] = false;
				}
		}
		$this->data['isAdmin'] = $this->isAdmin();
//		$this->data['image_src'] = $this->siteConfig->fb_image;
		$this->data['isLogin'] = $this->isUserLogin();
		$this->data['site_title'] = $this->siteConfig->site_title;
		$this->data['user'] = $this->user;
		$this->data['page'] = $this->uri->segment(1) . "." . $this->uri->segment(2);
		$this->data['site_config'] = $this->siteConfig;
		$this->data['url_styles'] = url_styles();

		//
	}

	protected function isRootAdmin() {
		return in_array($this->user->id, $this->config->item('root_admin'));
	}

	protected function isAdmin() {
		return in_array($this->user->group_id, $this->config->item('admin_group')) || $this->isRootAdmin();
	}

	protected function getUserInfo() {
		$this->load->model('model_user');
		$userId = $this->session->userdata('user_id');
		return $this->model_user->get_info($userId);
	}

	protected function isUserLogin() {
		if ($this->user !== false)
			return ($this->user->id !== $this->siteConfig->guest_id);
		return false;
	}

	protected function checkPermission() {
		if ($this->uri->segment(1) == 'cron')
			return true;
		$this->load->model('model_group');

		$group = $this->model_group->get_info($this->user->group_id);

		$permissions = json_decode($group->permissions);
		if (!$permissions)
			$permissions = array();
		$uri_string = $this->uri->uri_string();
		$segments = 1;
		if ($this->inAdminFolder) {
			$segments = 2;
			$uri_string = preg_replace('/([^\/]+\/[^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
		} else {
			$uri_string = preg_replace('/([^\/]+\/[^\/]+)(\/.+)?/i', '$1', $uri_string);
		}
		if ($this->uri->total_segments() == $segments)
			$uri_string .= '/index';

		$this->user->upload_text_image = ($this->isRootAdmin() || $group->upload_text_image == 1) ? TRUE : FALSE;
		return ($this->isRootAdmin() || in_array($uri_string, $permissions));
	}

	protected function load_view() {
		$this->load->view($this->style->folder . '/' . $this->config->item('layout_file'), $this->data);
	}

	private function get_user_location() {
		$location = isset($_COOKIE['location']) ? $_COOKIE['location'] : '';
		if (isset($this->data['locations'][$location]))
			return $location;
		return $this->siteConfig->location;
	}

	/**
	 * Upload anh len server
	 * @param $image_var
	 * @return stdClass
	 */
	protected function upload_image($image_var) {
		$config = image_get_upload_config($this->siteConfig);
		$this->load->library('upload', $config);
		if (!$this->upload->do_upload($image_var)) {
			//echo $this->upload->display_errors();
			return false;
		}
		// Upload va resize
		$upload_data = $this->upload->data();
		$resize_config = array(
			'source_image' => $upload_data['full_path'],
			'create_thumb' => TRUE,
			'maintain_ratio' => TRUE,
			'width' => $this->siteConfig->image_width,
			'height' => $this->siteConfig->image_height,
		);
		$this->load->library('image_lib', $resize_config);

		$this->image_lib->resize();
		$this->image_lib->clear();

		$resize_config['image_library'] = 'gd2';
		$resize_config['height'] = $this->siteConfig->thumb_height;
		$resize_config['width'] = $this->siteConfig->thumb_width;
		$resize_config['create_thumb'] = TRUE;
		$this->image_lib->initialize($resize_config);
		$this->image_lib->resize();

		$result = new stdClass();
		$result->path = $config['upload_path'] . '/' . $upload_data['file_name'];
		$result->thumb = preg_replace('/(.+)(\.(' . $this->siteConfig->image_types . '))/i', '$1_thumb$2', $result->path);
		return $result;
	}

	public function _delete_image($path) {
		unlink($path);
	}

	protected function form_is_valid() {
		$this->data['errors'] = array();
		if ($this->form_validation->run())
			return TRUE;
		foreach ($this->form_validation->_field_data as $field => $data) {
			$this->data['errors'][$field] = form_error($field);
		}
		return FALSE;
	}

	private function get_user_lang() {
		$this->load->model('model_lang');
		$id = request('lang');
		$this->user_lang = $this->model_lang->get_info($id);
		if ($this->user_lang === false)
			$this->user_lang = $this->model_lang->get_info($this->siteConfig->lang);
		if ($this->user_lang === false) {
			$languages = $this->model_lang->get_info(array('limit' => array(0, 1)));
			$this->user_lang = $languages[0];
		}
		setcookie('lang', $this->user_lang->id);
	}

	protected function get_new_product($limits) {
		$this->load->model('model_product');
		$products = $this->model_product->get_list(array(
			'where' => array('active' => 1),
			'order' => array('p.id', 'desc'),
			'limit' => array(0, 50),
				));
		$result_id = array_rand($product, $limits);
		$result = array();
		foreach ($result_id as $id) {
			$result[] = $products[$id];
		}
		return $result;
	}

}

?>
